<?php
/**
 * 直链访问
 */

require_once 'config/config.php';
require_once 'includes/db.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/config/installed.lock')) {
    header('Location: install.php');
    exit;
}

$link = trim($_GET['link'] ?? '');

if (empty($link)) {
    die('无效的直链');
}

try {
    $db = new Database();
    $file = $db->fetchOne("SELECT * FROM files WHERE direct_link = ?", [$link]);

    if (!$file) {
        die('文件不存在或链接已失效');
    }

    // 检查文件是否存在
    if (!file_exists($file['file_path'])) {
        die('文件已被删除或移动');
    }

    // 更新下载次数
    $db->query("UPDATE files SET download_count = download_count + 1 WHERE id = ?", [$file['id']]);

    // 设置下载头
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . rawurlencode($file['original_name']) . '"');
    header('Content-Length: ' . filesize($file['file_path']));
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');

    // 输出文件
    readfile($file['file_path']);
    exit;

} catch (Exception $e) {
    die('访问失败: ' . $e->getMessage());
}
